package com.zhl.model.excel.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdcardUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhl.common.vo.Result;
import com.zhl.model.excel.entity.Person;
import com.zhl.model.excel.entity.PersonExcelVo;
import com.zhl.model.excel.mapper.PersonMapper;
import com.zhl.model.excel.service.ExcelStyleUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 凌晨
 * @Title: ParseDataController
 * @Description TODO
 * @date： 2022/2/26 15:13
 * @version： V1.0
 */
@RestController
@Slf4j
public class ParseDataController {

    @Autowired
    private PersonMapper personMapper;

    @PostMapping("/parseData")
    public Result readData(@RequestBody String content){
        String[] split = content.split("\n");
        for (String s : split) {
            log.info("游客信息为："+s);
            String name = s.replaceAll("\\s*","").replaceAll("[^(\\u4e00-\\u9fa5)]","");
            log.info("过滤出汉字：" + name);
            String idCard = s.replaceAll("\\s*","").replaceAll("[^(0-9)]","");
            log.info("过滤出数字：" + idCard);
//            String[] s1 = s.split(" ");
            Person person = new Person();
            person.setName(name);
            if(idCard.length() < 18){
                idCard = idCard + "x";
            }
            person.setIdCard(idCard);
            // 获取生日
            String birth = IdcardUtil.getBirth(idCard);
            // 获取年龄
            Integer age = IdcardUtil.getAgeByIdCard(idCard);
            int sex = IdcardUtil.getGenderByIdCard(idCard);
            String province = IdcardUtil.getProvinceByIdCard(idCard);
            log.info("\n 生日："+birth);
            log.info("\n 年龄："+age);
            log.info("\n 性别："+sex);
            log.info("\n 省份："+province);
            Short yearByIdCard = IdcardUtil.getYearByIdCard(idCard);
            Short monthByIdCard = IdcardUtil.getMonthByIdCard(idCard);
            Short dayByIdCard = IdcardUtil.getDayByIdCard(idCard);
            person.setAge(age);
            person.setSex(sex == 1 ? "男" : "女");
            person.setProvince(province);

            String month = monthByIdCard.toString().length() == 1 ? "0"+monthByIdCard.toString() : monthByIdCard.toString();
            String day = dayByIdCard.toString().length() == 1 ? "0"+dayByIdCard.toString() : dayByIdCard.toString();
            person.setBirthday(yearByIdCard+"-"+ month +"-"+day);
            person.setCreateTime(new Date());
            personMapper.insert(person);
        }
        return Result.ok();

    }

    /**
     * 导出excel
     * @return
     */
    @GetMapping("/personExport")
    public Result easyPoiExport(){
        String dir = System.getProperty("user.dir");
        log.info("用户工作目录：{}",dir);
        long startTime = System.currentTimeMillis();
        String currentDate = DateUtil.format(new Date(), "yyyyMMddHHmmss");

//        LambdaQueryWrapper<Person> queryWrapper = Wrappers.lambdaQuery();
        List<PersonExcelVo> personList = personMapper.selectAll();

        ExportParams exportParams = new ExportParams(null,"游客统计信息");
        exportParams.setStyle(ExcelStyleUtil.class);
        Workbook workbook = ExcelExportUtil.exportBigExcel(exportParams,
                PersonExcelVo.class, personList);
        FileOutputStream fos = null;
        String fileName = dir + currentDate+".xlsx";
        try {
            fos = new FileOutputStream(fileName);
            workbook.write(fos);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                fos.close();
                //重复导出失败，每次关闭这个即可Stream closed
                ExcelExportUtil.closeExportBigExcel();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        log.info("导出excel耗时==="+(System.currentTimeMillis()-startTime)+"毫秒");
        return Result.ok();
    }

    @PostMapping("clearData")
    public Result clearData(){
        LambdaQueryWrapper<Person> queryWrapper = Wrappers.lambdaQuery();
        personMapper.delete(queryWrapper);
        return Result.ok();
    }

    public static void main(String[] args) {
        String a="陈  \n" +
                "晓鹏，500236199210158888";
        String regEx="[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(a);
        System.out.println( m.replaceAll("").trim());
    }




}
